/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.generalfile.servlet;

import cn.net.greenet.generalfile.logic.DataChange;
import cn.net.greenet.generalfile.logic.GeneralFileProcess;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;

/**
 * 从数据库中生成IP 地址库文件到SFTP
 *
 * @author ShiYun,2014/11/04
 */
@WebServlet(name = "GetIpBankFromDB2File", urlPatterns = {"/common/produce_ip_bank"})
public class GetIpBankFromDB2File extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String MessageType = request.getParameter("MessageType");
        String policy_instance = request.getParameter("policy_instance");
        String dstPath = request.getParameter("dstPath");

        boolean result = false;
        JSONObject one = new JSONObject();
        GeneralFileProcess pro = new GeneralFileProcess(null, MessageType, policy_instance, dstPath);
        String sql = GeneralFileProcess.QUERY_IP_BANKS;

        //获取文件路径和指定文件名
        pro.getProperties();
        dstPath = pro.getCommonFilePath();
        if (dstPath.endsWith("/")) {
            dstPath = dstPath + pro.getIpAddressLibrary();
        } else {
            dstPath = dstPath + File.separator + pro.getIpAddressLibrary();
        }
        // 获取数据库链接
        pro.init();
        ResultSet rs = pro.query(sql);
        try {
            String areaName = null;
            String startIP = null;
            String endIP = null;
            StringBuilder sb = new StringBuilder();
            while (rs != null && rs.next()) {
                areaName = rs.getString("areaName");
                startIP = rs.getString("startIP");
                endIP = rs.getString("endIP");
                int type = rs.getInt("type");
                if (type == 1) {
                    type = 4;
                } else {
                    type = 6;
                }
                String IPtype = DataChange.dec2Hex_2(type);
                sb.append(IPtype).append("\t").append(startIP).append("\t").append(endIP).append("\t").append(areaName);
                if (!rs.isLast()) {
                    sb.append("\n");
                }
            }
            FileUtils.writeStringToFile(new File(dstPath), sb.toString(), false);
            result = true;
        } catch (SQLException ex) {
            Logger.getLogger(GetWebFromDB2File.class.getName()).log(Level.SEVERE, null, ex);
        }
        //关闭数据库连接
        pro.close();
        one.put("result", result);
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println(one.toString());
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
